package com.jmag.nop.service.common.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

/**
 * @ClassName AESUtil
 * @Description TODO
 * @Author JMAG
 * @Version 1.0
 **/
public class AESUtil {
    private static final String UTF8 = "UTF-8";
    private static final String ALGORITHM = "AES";
    private static final String ALGORITHM_CIPHER = "AES/ECB/PKCS5Padding";
    private static final int LIMIT_LEN = 16;

    public AESUtil() {
    }

    public static SecretKey getSecretKey(String password) {
        byte[] passwordData = password.getBytes();
        if (passwordData.length > 16) {
            throw new IllegalArgumentException("password 长度必须小于等于16");
        } else {
            byte[] keyData = new byte[16];
            System.arraycopy(passwordData, 0, keyData, 0, passwordData.length);
            return new SecretKeySpec(keyData, "AES");
        }
    }

    public static byte[] encrypt(byte[] data, String password) throws Exception {
        SecretKey secretKey = getSecretKey(password);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(1, secretKey);
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] data, String password) throws Exception {
        SecretKey secretKey = getSecretKey(password);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(2, secretKey);
        return cipher.doFinal(data);
    }

    public static String encryptToBase64String(String content, String password) throws Exception {
        byte[] data = content.getBytes("UTF-8");
        byte[] result = encrypt(data, password);
        return Base64.encodeBase64String(result);
    }

    public static String decryptFromBase64String(String base64String, String password) throws Exception {
        byte[] data = Base64.decodeBase64(base64String);
        byte[] contentData = decrypt(data, password);
        return new String(contentData, "UTF-8");
    }

    public static String encryptToHex(String content, String password) throws Exception {
        byte[] data = content.getBytes("UTF-8");
        byte[] result = encrypt(data, password);
        return Hex.encodeHexString(result);
    }

    public static String decryptFromHex(String hex, String password) throws Exception {
        byte[] data = Hex.decodeHex(hex);
        byte[] contentData = decrypt(data, password);
        return new String(contentData, "UTF-8");
    }
}
